﻿using MiniFox.Components;
using RazorEngineCore;
using System.Text;
using TemplateEngine.Models;
using TemplateEngine.Providers;

namespace TemplateEngine
{
    /// <summary>
    /// 
    /// </summary>
    public class DefaultTemplateService : TemplateServiceBase
    {
        /// <summary>
        /// 
        /// </summary>
        public DefaultTemplateService()
        {
        }

        /// <summary>
        /// s
        /// </summary>
        /// <param name="encoding"></param>
        public DefaultTemplateService(Encoding encoding) : base(encoding)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        [AutoWired]
        public ITemplateDataProvider DataProvider
        {
            get; set;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <param name="templateContent"></param>
        /// <returns></returns>
        public override string Resolve(object model, string templateContent)
        {
            var engine = new RazorEngine();
            var template = engine.Compile(templateContent);
            string body = template.Run(model);
            return body;
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <param name="templateContent"></param>
        /// <returns></returns>
        public override async Task<string> ResolveAsync(object model, string templateContent)
        {
            var engine = new RazorEngine();
            var template = await engine.CompileAsync(templateContent);
            string body = await template.RunAsync(model);
            return body;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected override TemplateDo GetTemplate(string name)
        {
            TemplateDo templateDo = this.DataProvider.GetTemplate(name);
            return templateDo;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected override async Task<TemplateDo> GetTemplateAsync(string name)
        {
            TemplateDo templateDo = await this.DataProvider.GetTemplateAsync(name);
            return templateDo;
        }

    }

}
